package Q5;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {

    public static void main(String[] args) {
        //1.创建Socket类型的对象并提供服务器的主机名和端口
        Socket client = null;
        Scanner sc = null;
        File file = null;
        ObjectOutputStream send = null;
        ObjectInputStream receive = null;
        Message message;

        try {
            client = new Socket("127.0.0.1", 6666);
            System.out.println("客户端已经连接到服务器..........");
            sc = new Scanner(System.in);
            send = new ObjectOutputStream(client.getOutputStream());
            //2.使用输入输出流进行通信
            //开启线程并利用线程接收消息
            Thread thread =new  Thread(new ClientThread(client));
            thread.start();
            while (true){
                System.out.println("请输入想要发送的数据内容：");
                String content = sc.next();
                System.out.println("请输入想要发送的文件路径(如果无想要发送的文件请输入no)：");
                String file_path = sc.next();
                if(file_path.equalsIgnoreCase("no")){
                    message = new Message(content, file, client.getInetAddress());
                }else{
                    message = new Message(content,new File(file_path), client.getInetAddress());
                }
                send.writeObject(message);
                System.out.println("已向服务器发送信息!");
                if(content.equalsIgnoreCase("Bye")){
                    System.out.println("客户端已下线");
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //3.关闭Socket并释放有关的资源

            if(null != sc){
                sc.close();
            }
            if(null != client){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
